<template>
  <!--  <ContentWrap>-->
  <!--    <div style="display: flex; align-items: center">-->
  <!--      <div style="width: 10px; height: 24px; background-color: #1890ff"></div>-->
  <!--      <h3 style="margin-left: 6px">EQIM配置启动</h3>-->
  <!--      <el-switch-->
  <!--        v-model="form.enabled"-->
  <!--        style="margin-left: 50px"-->
  <!--        size="large"-->
  <!--        inline-prompt-->
  <!--        :active-icon="Check"-->
  <!--        :inactive-icon="Close"-->
  <!--        @change="onSwithChange"-->
  <!--      />-->
  <!--    </div>-->
  <!--  </ContentWrap>-->

  <ContentWrap v-loading="loading" v-if="setView === 'list'">
    <div style="position: relative">
      <ContentWrapForm
        style="padding: 20px 0px; border: none; height: 15px"
        :title="'地震过滤设置'"
      ></ContentWrapForm>
      <el-button
        style="position: absolute; right: 20px; top: 13px"
        type="primary"
        v-show="isbut"
        @click="UpdateRoot"
        >修改
      </el-button>
    </div>

    <el-divider style="padding: 0; margin: 0" />
    <el-form :model="form" label-position="top" label-width="auto" :inline="true">
      <el-row>
        <el-form-item label="台网代码:" prop="networkCodes">
          <el-checkbox-group v-model="twCodesbox" :disabled="isView">
            <el-checkbox label="CC" value="CC" />
            <el-checkbox label="CD" value="CD" />
            <el-checkbox label="AU" value="AU" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="magnitude" label="震级大于等于:">
          <el-input
            v-model="form.magnitude"
            placeholder="请输入"
            style="width: 260px"
            :disabled="isView"
          ></el-input>
        </el-form-item>
        <el-form-item prop="distance" label="区域外扩距离:">
          <el-input
            v-model="form.distance"
            placeholder="请输入"
            style="width: 260px"
            :disabled="isView"
          ></el-input>
        </el-form-item>

        <el-col :span="24">
          <el-form-item prop="type" label="区域范围:">
            <el-radio-group v-model="form.type" @change="handleTypeChange" :disabled="isView">
              <el-radio :label="0">上传区域文件</el-radio>
              <el-radio :label="1" @click="provinceRef">按行政区划选择</el-radio>
            </el-radio-group>
            <ProvinceCity
              style="margin-top: 10px"
              ref="provinceRef"
              :regionLists="form.regionList"
              @querySelect="querySelect"
              v-if="!isProvinceCityDisabled"
              :disabled="isProvinceCityDisabled"
            />
          </el-form-item>
          <el-form-item v-if="form.type === 0" label="" style="margin-left: 60px; width: 100%">
            <UploadFile
              v-model="form.fileNames"
              :updateUrl="uploadUrl"
              :downloadFileUrl="downloadFileUrl"
              @uploadSuccess="uploadSuccess"
              @removeFile="removeFile"
              :limit="1"
              :disabled="isProvinceCityDisabled"
            ></UploadFile>
          </el-form-item>
          <el-form-item v-if="form.type === 1" label="" style="margin-left: 60px">
            {{ regionLists }}
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <LoadMap :fileidInfo="fileidInfo" style="height: 400px" />
  </ContentWrap>
  <div v-show="showbuttton" style="margin-top: 72px; display: flex; justify-content: center">
    <el-col class="el-colfoot">
      <el-button @click="close">关闭</el-button>
      <el-button type="primary" @click="save" v-if="!isView">保存</el-button>
    </el-col>
  </div>

  <ViewComponent
    v-if="setView === 'setUpdate'"
    :id="form.id"
    @updatecreate="getUpdate"
    @savecreate="getsave"
  ></ViewComponent>
</template>

<script setup>
import UploadFile from '@/views/responseLevel/populationDensity/create/UploadFile.vue'
import ProvinceCity from '@/views/responseLevel/populationDensity/create/provinceCity.vue'
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import ViewComponent from '@/views/earthquake/eqim/view.vue'
import { ElMessage } from 'element-plus'
import * as eqimApi from '@/api/earthquake/eqim'
import * as timingTrigger from '@/api/earthquake/timingTrigger'
import * as userInfoApi from '@/api/login/index'

const { currentRoute, push } = useRouter() // 路由
const uploadUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/att/uploadShpFile1')
const downloadFileUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/att/downLoadFile')
const route = useRoute()
const loading = ref(false)
const show = ref(true)
const twCodesbox = ref([])
const isView = ref(true)
const isProvinceCityDisabled = ref(true)
const isbut = ref(true)
const setView = ref('list')

const showbuttton = ref(false)
const form = ref({
  id: '',
  pulsarCheck: false,
  enabled: false,
  pulsarUrl: '',
  pulsarToken: '',
  pulsarTopic: '',
  dbCheck: false,
  dbHost: '',
  dbUsername: '',
  database: '',
  dbCheckInterval: null,
  dbPort: null,
  dbPassword: '',
  dbCharset: '',
  webCheck: false,
  checkUrl: '',
  webCheckInterval: null,
  twCodes: '',
  magnitude: '',
  pageNo: 0,
  pageSize: 0,
  type: null,
  distance: null,
  areaFileId: '',
  fileNames: [],
  regionList: []
})
const provinceRef = ref()
const regionLists = ref('')
const uploadAction = 'your-upload-action-url'
const uploadHeaders = {
  Authorization: 'your-upload-token'
}

//重置数据
const resetForm = () => {
  twCodesbox.value = []
  form.value.magnitude = ''
  form.value.distance = null
  form.value.areaFileId = ''
  form.value.type = null
}

//初始化 type 0 -- 临时表 1 ---正式表 owner public公库 private四库
const fileidInfo = ref({
  fileid: '',
  type: 1,
  query: {
    tableName: 'earthquake_shp',
    fields: 'id,p_id,province,city',
    owner: 'public'
  }
})

//初始化数据 isFirst 是否第一次进入 修改true
const getEqim = async (isFirst) => {
  loading.value = true
  const res = await eqimApi.list()
  if (res.length > 0) {
    const twCodes = res[0].twCodes.split(',')
    if (twCodes.length > 0) {
      twCodes.forEach((item) => {
        twCodesbox.value.push(item)
      })
    }
    if (!isFirst) {
      fileidInfo.value.type = 1
      fileidInfo.value.query.tableName = 'earthquake_shp'
      fileidInfo.value.query.fields = 'id,p_id,province,city'
      fileidInfo.value.fileid = 'eqim_' + res[0].id
    }

    form.value = res[0]
  }
  if (form.value !== undefined) {
    if (form.value.fileNames) {
      form.value.fileNames = form.value.fileNames.map((item) => {
        return { name: item, url: form.value.areaFileId, attachId: form.value.areaFileId }
      })
    } else {
      form.value.fileNames = []
    }
    if (form.value.regionList) {
      let data = []
      form.value.regionList.forEach((item) => {
        if (item.city == 'undefined' || !item.city) data.push(item.province)
        else data.push(item.province + '-' + item.city)
      })
      regionLists.value = data.join(',')
    } else {
      form.value.regionList = []
    }
  }
  loading.value = false
}

// 启用
const onSwithChange = async (value) => {
  if (form.value.id === '') {
    ElMessage.error('请先添加EQIM配置')
    form.value.enabled = false
    return
  }
  if (value) {
    console.log('已启用EQIM配置')
    form.value.enabled = value
    await eqimApi.updateEnable(form.value)
  } else {
    console.log('已关闭EQIM配置')
    form.value.enabled = value
    await eqimApi.updateEnable(form.value)
  }
}

// 修改
const UpdateRoot = async () => {
  const userInfo = await userInfoApi.getInfo()
  if (userInfo.user.divisionCode === 'root') {
    setView.value = 'setUpdate'
  } else {
    isView.value = false
    isbut.value = false
    isProvinceCityDisabled.value = false
    showbuttton.value = true
  }
}

//删除eqim
const delRoot = async () => {
  let ids = [form.value.id]
  await eqimApi.deleteEqim(ids)
  await getEqim()
}

// 上传成功
const uploadSuccess = (file) => {
  form.value.areaFileId = file[0].attachId
  fileidInfo.value.type = 0
  fileidInfo.value.query.tableName = 'temp_shp_data'
  fileidInfo.value.query.fields = 'id'
  fileidInfo.value.query.owner = 'public'
  fileidInfo.value.fileid = file[0].id
}

// 删除文件
const removeFile = (file) => {
  form.value.areaFileId = ''
  timingTrigger.deleteFile(file.attachId)
  fileidInfo.value.fileid = ''
}

//区域范围
const handleTypeChange = (val) => {
  if (!provinceRef.value) return
  if (val === 1) {
    provinceRef.value.open()
  } else {
    provinceRef.value.close()
    form.value.regionList = []
    regionLists.value = ''
    cityListCancel()
  }
}

const cityListCancel = () => {
  fileidInfo.value = {
    type: 0,
    query: {
      tableName: '',
      fields: ''
    },
    fileid: null
  }
}

//按行政区域选择
const querySelect = (value) => {
  let data = []
  value.forEach((item) => {
    if (item.city) {
      data.push(item.province + '-' + item.city)
    } else {
      data.push(item.province)
    }
  })
  regionLists.value = data.join(',')
  form.value.regionList = value
  cityList()
}

//城市列表值
const cityList = async () => {
  if (form.value.type !== 1) return
  let citydatas = {
    city: regionLists.value
  }
  try {
    const response = await eqimApi.postCityList(citydatas)
    fileidInfo.value.query.tableName = 'temp_shp_data'
    fileidInfo.value.query.fields = 'id'
    fileidInfo.value.type = 0
    fileidInfo.value.query.owner = 'public'
    fileidInfo.value.fileid = response.id
  } catch (error) {
    console.error('请求后端API时发生错误:', error)
  }
}

// 保存设置的逻辑
const save = async () => {
  loading.value = true
  form.value.twCodes = twCodesbox.value.length > 0 ? twCodesbox.value.join(',') : ''
  form.value.fileNames = []
  if (!form.value.type) form.value.regionList = []
  else form.value.areaFileId = null
  await eqimApi.updateEnable(form.value).then((res) => {
    if (res === 1) {
      getEqim(true)
    } else {
      return ElMessage.warning(res.msg)
    }
  })
  loading.value = false
  showbuttton.value = false
  isbut.value = true
  isView.value = true
  isProvinceCityDisabled.value = false
}

//关闭
const close = () => {
  getEqim()
  showbuttton.value = false
  isbut.value = true
  isView.value = true
  isProvinceCityDisabled.value = true
}

const getUpdate = (e) => {
  setView.value = e
}

const getsave = () => {
  getEqim()
  setView.value = 'list'
}

onMounted(() => {
  getEqim()
})
</script>

<style scoped>
.add-eqim-settings {
  background-color: #fff;
  padding: 20px;
}

/* 头部标题 */
.add-eqim-top {
  background-color: #fff;
  height: 60px;
  line-height: 60px;
}

.add-eqim-top h2 {
  margin-left: 50px;
}

/* 主体内容区域 */
.add-eqim-content {
  background-color: #fff;
  margin-top: 40px;
}

.add-eqim-content-title {
  display: flex;
  align-items: center;
}

.add-eqim-content-title div {
  width: 10px;
  height: 26px;
  background-color: #1890ff;
}

.add-eqim-content-title h3 {
  margin-left: 8px;
}

.add-eqim-content-title2 {
  display: flex;
  align-items: center;
  height: 70px;
  line-height: 70px;
}

/* Pulsar区域 */
.add-eqim-content-Pulsar {
  margin-top: 60px;
}

/* 底部区域 */
.add-eqim-bottom {
  background-color: #fff;
}

.add-eqim-bottom-title3 div {
  width: 10px;
  height: 26px;
  background-color: #1890ff;
}

.add-eqim-bottom-title3 {
  display: flex;
  align-items: center;
  height: 70px;
  line-height: 70px;
}

.add-eqim-bottom-title3 h3 {
  margin-left: 8px;
}

.add-eqim-bottom-filter {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.el-form-item {
  width: 280px;
  height: 60px;
  margin-top: 30px;
}

.el-colfoot {
  position: absolute;
  left: 0px;
  width: 100%;
  height: 72px;
  opacity: 1;
  bottom: 0;
  background: #ffffff;
  box-sizing: border-box;
  text-align: right;
  padding: 20px;
  z-index: 3;
}
</style>
